package com.itheima.controller;

import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author weizhongli
 * @Date 2020/4/24
 * @Version v1.0
 * @Description
 **/
@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "defaultFallback") //设置全局服务降级的方法，配置属性
public class Controller {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;


    @GetMapping("/findUserById/{id}")
    @HystrixCommand(fallbackMethod = "fallBackMethod")
    //@HystrixCommand
    public User findUserById(@PathVariable Integer id) {

        /*
         * 1.url硬编码
         * 2.单点故障 负载问题
         * 3.消费者无法得知生产者的健康状态
         * */

        //一：url硬编码
        //String url = "http://localhost:9091/user/findUserById/" + id;

        //二：解决硬编码
        //uri	"http://localhost:9091"
        //1.获取服务列表
      /*  List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        ServiceInstance serviceInstance = instances.get(0);
        //2.获取uri
        URI uri = serviceInstance.getUri();
        //3.url拼接
        String url = uri+"/user/findUserById/" + id;
        System.out.println("url拼接后："+url);*/

        //三：解决负载问题  根据服务应用名称来调用
        String url = "http://provider-service/user/findUserById/" + id;
        User user = restTemplate.getForObject(url, User.class);
        /*User user = consummerService.findUserById(id);*/
        return user;
    }


    //熔断方法
    /*
     * 要求：
     * 1.返回数据类型必须与原方法一致
     * 2.传入参数必须与原方法一致
     * */
    public User fallBackMethod(Integer id) {
        User user = new User();
        user.setId(id);
        user.setName("熔断方法");
        return user;
    }


    /*
     *全局服务降级方法
     * 方法特点：
     * 参数不填
     * 返回值：必须与被降级的方法保持一致
     * 方法名称：可以自定义
     * */
    public User defaultFallback(){
        User user = new User();
        user.setNote("全局服务的降级方法");
        return user;
    }

    /*
     * 获取服务列表信息
     * */
    @GetMapping("/getServices")
    public List<ServiceInstance> getServices() {
        //uri	"http://localhost:9091"
        List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        return instances;
    }
}
